package com.sq.partner.manager.service.impl.credit;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import com.sq.partner.manager.common.Constants;
import com.sq.partner.manager.common.DictCache;
import com.sq.partner.manager.common.Result;
import com.sq.partner.manager.common.exception.AppException;
import com.sq.partner.manager.dao.IFacadeUserDao;
import com.sq.partner.manager.dao.IGatewayAgentInfoMtDao;
import com.sq.partner.manager.dao.IGatewayChannelAppDao;
import com.sq.partner.manager.dao.IGatewayChannelInfoConfigDao;
import com.sq.partner.manager.dao.IGatewaySubChannelDao;
import com.sq.partner.manager.mybatis.model.DictDto;
import com.sq.partner.manager.mybatis.model.FacadeUser;
import com.sq.partner.manager.mybatis.model.GatewayChannelApp;
import com.sq.partner.manager.mybatis.model.GatewayChannelInfo;
import com.sq.partner.manager.mybatis.model.GatewaySubChannel;
import com.sq.partner.manager.mybatis.model.GatewayUser;
import com.sq.partner.manager.mybatis.model.TradAgentInfo;
import com.sq.partner.manager.mybatis.model.TradSaleAgent;
import com.sq.partner.manager.service.IGatewayClearCacheManager;
import com.sq.partner.manager.service.credit.CreditInfomationService;
import com.sq.partner.manager.service.impl.IGatewayAgentInfoMtServiceImpl;
import com.sq.partner.manager.util.ExcelUtil;
import com.sq.partner.manager.util.LogUtil;
import com.sq.partner.manager.util.MD5Util;
import com.sq.partner.manager.util.StrUtil;
@Service
public class CreditInfomationSeviceImpl implements CreditInfomationService {
	private static Logger logger = LogUtil.getLog(CreditInfomationSeviceImpl.class); 
	@Resource
	private IGatewayAgentInfoMtDao agentInfoMtDao;
	@Resource
	private IGatewayChannelInfoConfigDao channelInfoConfigDao;
	@Resource
	private IFacadeUserDao userdao;
	@Resource
	private IGatewaySubChannelDao subChannelDao;
	@Resource
	IGatewayChannelAppDao gatewayChannelAppDao;
	@Resource
	IGatewayClearCacheManager gatewayClearCacheManager;
	@Resource
	private IFacadeUserDao batchMtFacadeUserDao;
	private String credit="";//信保
	//检查sheet 是否满足业务规则校验,检查个人代理类型的
    List<String> userCodes=new ArrayList<String>();
	Map<String, String> countMap=new HashMap<String, String>();
	@Override
	public Result saveAgentMtInfoAsCredit(String flag, String agentType,
			String userCode, String channelCode, String subChannelCode,
			String dptCde, String agentNo, String protocolNo,
			String serviceCode, String serviceName, String empNo,
			String empName, String teamCode, String teamName, String userName,
			String cardApplicant, String channleCode, String channleType,
			String newBsnsType, String categoryCode, String zone,
			String organization, String branch, String branchName, Long id,
			GatewayUser user, String cbrkrname, String coprcod, String key1,
			String key2, String key3, String key4, String key5,
			String unionType, String manag_code, 
			String manag) throws Exception {
		String temSubCode="";
		String regexM = "[A-Za-z0-9_]+";//匹配正则数字、字符、下划线
		GatewayChannelInfo channelInfo = new GatewayChannelInfo();
		channelInfo.setChannelCode(channelCode);
		GatewayChannelInfo channelInfoFind = channelInfoConfigDao.queryByChannelInfo(channelInfo);
		//总对总
		if("4".equals(agentType)){
			//首先先检查否存在该子机构的信息
			GatewaySubChannel subChannelInfo = new GatewaySubChannel();
			if(StrUtil.isNotEmpty(zone)){
				temSubCode = channelCode.concat(zone).concat(branch);
				subChannelInfo.setSubChannelCode(temSubCode);
			}else{
				temSubCode = branch;
				subChannelInfo.setSubChannelCode(temSubCode);
			}
			subChannelInfo.setSubChannelName(branchName);
			subChannelInfo.setParentChannelCode(channelCode);
			subChannelInfo.setZone(zone);
			subChannelInfo.setBranch(branch);
			subChannelInfo.setBranchName(branchName);
			subChannelInfo.setFkChannelCode(channelCode);
			subChannelInfo.setStatus("1");
			subChannelInfo.setOperUser(user.getUserid());
			subChannelInfo.setOperTime(new Date());
			Map<String, String> map1=new HashMap<String, String>();
			map1.put("subChannelCode", subChannelInfo.getSubChannelCode());
			map1.put("chanelCode", subChannelInfo.getFkChannelCode());
			if("save".equals(flag)){
				if(null!=subChannelDao.querySubChannelInfoByCondition(map1)){
					if(temSubCode.equals(branch)){
						return Result.error("该网点代码已经存在,请更换");
					}else{
						return Result.error("本合作伙伴下的区域代码和网点代码配置重复,请检查");
					}
				}
				//总对总界面出单处理
				if(null!=channelInfoFind && "1".equals(channelInfoFind.getTransType())){
					if(StrUtil.isNotEmpty(userCode) && StrUtil.isEmpty(userName)){
						return Result.error("姓名不允许为空，请检查");
					}else if(StrUtil.isNotEmpty(userName) && StrUtil.isEmpty(userCode)){
						return Result.error("用户名不允许为空，请检查");
					}else if(StrUtil.isNotEmpty(userName) && StrUtil.isNotEmpty(userCode)){
						if(!userCode.matches(regexM)){
							return Result.error("输入的代理人用户名格式不正确，正确格式只能录入字母、数字、下划线组合的字符串");
						}
						FacadeUser serchUser = new FacadeUser();
						serchUser.setUserCode(userCode);
						List<FacadeUser> users = userdao.queryUsersByMapUser(serchUser);
						if(users!=null&&!users.isEmpty()){
							return Result.error("用户名 "+userCode+"已存在,请更换");
						}
						FacadeUser facadeUser = new FacadeUser();
						facadeUser.setUserCode(userCode);
						facadeUser.setUserName(userName);
						facadeUser.setUserTypeCode(agentType);
						facadeUser.setfKSubChannelCode(subChannelInfo.getSubChannelCode());
						facadeUser.setStatus(1);
						facadeUser.setFkChannelCode(channelCode);
						facadeUser.setUserPwd(MD5Util.md5(userCode));
						facadeUser.setOperTime(new Date());
						facadeUser.setOperUser(user.getUserid());
						userdao.addUser(facadeUser);
					}
				}
				if("save".equals(flag)){
					subChannelDao.save(subChannelInfo);
				}
			}else if("update".equals(flag)){
				if(StrUtil.isNotEmpty(userCode)){
					Map<String,String> map = new HashMap<String, String>();
					map.put("userCode", userCode);
					FacadeUser temUser = userdao.queryUserCountByMap(map);
					if(null!=temUser){
						FacadeUser facadeUserToDB = new FacadeUser();
						facadeUserToDB.setUserid(temUser.getUserid());
						facadeUserToDB.setUserName(userName);//总对总只能修改出单用户姓名
						userdao.saveUser(facadeUserToDB);//更新操作时处理
					}
				}
				if("update".equals(flag)){
					subChannelDao.update("updateGatewaySubChannel", subChannelInfo);
				}
			}
		}
		TradAgentInfo agentMtInfo = new TradAgentInfo();
		agentMtInfo.setAgentType(agentType);
		agentMtInfo.setUserCode(userCode);
		agentMtInfo.setUserName(userName);
		agentMtInfo.setChannelCode(channelCode);
		if("4".equals(agentType)){
			agentMtInfo.setSubChannelCode(temSubCode);
		}
		agentMtInfo.setDptCde(dptCde);
		agentMtInfo.setAgentNo(agentNo);
		agentMtInfo.setProtocolNo(protocolNo);
		agentMtInfo.setServiceCode(serviceCode);
		agentMtInfo.setEmpNo(empNo);
		agentMtInfo.setTeamCode(teamCode);
		agentMtInfo.setTeamName(teamName);
		//add by menyanlei 新意见险新增
		agentMtInfo.setServiceName(serviceName);
		agentMtInfo.setEmpName(empName);
		//add  end
		agentMtInfo.setCardApplicant(cardApplicant);
		agentMtInfo.setChannleCode(channleCode);
		agentMtInfo.setChannleType(channleType);
		agentMtInfo.setNewBsnsType(newBsnsType);
		agentMtInfo.setCategoryCode(categoryCode);
		agentMtInfo.setOperTime(new Date());
		agentMtInfo.setCoprcod(coprcod);
		agentMtInfo.setCbrkrname(cbrkrname);
		agentMtInfo.setOperUser(user.getUserid());
		agentMtInfo.setOrganization(organization);
		//add by qinjiawei 信保新增
		agentMtInfo.setManag_code(manag_code);
		agentMtInfo.setManag(manag);
		
		if("save".equals(flag)){
			if(agentInfoMtDao.addAgentInfo(agentMtInfo)){
				clearAllCacheByChannelCode(channelCode);
				return Result.success("添加成功！");
			}
			return Result.error("添加失败！");
		}else if("update".equals(flag)){
			agentMtInfo.setId(id);
			if(agentInfoMtDao.updateAgentInfo(agentMtInfo)){
				clearAllCacheByChannelCode(channelCode);
				return Result.success("更新成功！");
			}
			return Result.error("更新失败！");
		}else{
			return Result.error("操作失败，系统检查出非法数据传入，请检查！");
		}
	}

	//合作伙伴配置缓存管理公共方法
		public void clearAllCacheByChannelCode(String channelCode) throws Exception {
			//查询应用by：channelCode
			List<GatewayChannelApp> appLs = gatewayChannelAppDao.queryChannelAppInfoListByChannelCode(channelCode);
			if(null!=appLs && appLs.size()>0){
				for(GatewayChannelApp tem :appLs){
					gatewayClearCacheManager.clearAllCache(tem.getAppId());
				}
			}
		}
		
		@Override
		public List<InputStream> getFileInputStream(MultipartFile[] myfiles) throws AppException {
			List<InputStream> inputStreams=new ArrayList<InputStream>();
			try {
				for(MultipartFile file : myfiles){
					String fileNameStr = file.getOriginalFilename();
					int lastDotIndex = fileNameStr.lastIndexOf(".");
					if(-1==lastDotIndex){
						throw new AppException("请选择扩展名为 .xls 的文件上传");
					}else{
						String extName = fileNameStr.substring(lastDotIndex+1,fileNameStr.length());
						if(!"xls".equals(extName.toLowerCase())){
							throw new AppException("请选择扩展名为 .xls 的文件上传");
						}
					}
					if (file.isEmpty()) {
						throw new AppException("上传失败，上传文件不能为空！");
					} else {
						InputStream inputStream = file.getInputStream();
						inputStreams.add(inputStream);
					}
				}
			} catch (IOException e) {
				throw new AppException("上传错误!请稍后重试");
			}
			return inputStreams;
		}
		
		@Override
		public synchronized void insertFinalPassDataToDB(InputStream inputStream,GatewayUser user,String agentType, HttpSession session) throws Exception {
			//一、校验excel数据是否合法;
			HSSFWorkbook workBook = null;
			List<TradAgentInfo> list = null;
			try{
				workBook = new HSSFWorkbook(inputStream);
				list = new ArrayList<TradAgentInfo>();
			}catch(Exception e){
				logger.info("上传失败，上传文件内容有误",e);
				throw new AppException("上传失败，上传文件内容有误!");
			}
			//读取模板第一个sheet表格的数据
			HSSFSheet sheet = workBook.getSheetAt(0);
			int sheets=workBook.getNumberOfSheets();
			boolean flag=false;
			if(sheets>1){
				String sheetName=workBook.getSheetName(1);
				if(StrUtil.isNotEmpty(sheetName)&&sheetName.contains("销售信息")){
					flag=true;
				}
			}
			int lastRowNumber = sheet.getLastRowNum();
			int lastRow=0;
		    
			if("3".equals(agentType)||"4".equals(agentType)||"5".equals(agentType)){
				if(sheet!=null){
					lastRow=sheet.getLastRowNum();
				}
			}
			boolean content=false;
			if("5".equals(agentType)){
				content=lastRowNumber<=3;
			}else{
				content=lastRowNumber<=1;
			}
			Map<String, List<TradAgentInfo>> agentMap=new HashMap<String, List<TradAgentInfo>>();
			if(content&&lastRow<3){
				throw new AppException("上传失败，上传excel文件内容为空或模板非最新模板");
			}else if(lastRowNumber>5001||lastRow>5001){
				throw new AppException("为了用户体验，一次最多只能导入5000条数据");
			}
			//1.导入DB前，先检查excel是否满足业务需求规则；
			if("4".equals(agentType)&&lastRowNumber>1){
				list = importPreCheckSubBranchAgentTypeIsPassBusinessRule(sheet,user);
				StringBuffer errorBuf = new StringBuffer();
				Map<String,Integer> excelIndexSubChannelInfo = new HashMap<String,Integer>();
				Map<String,Integer> excelIndexChannelInfo = new HashMap<String,Integer>();
				List<TradAgentInfo> errorUserMsg = null;
				List<TradAgentInfo> allChannelInfo = null;
				//总对总交易类型合作伙伴容器
				List<String> isFacadeChannelInfoLs = null;
				List<TradAgentInfo> isFacadeAgentList = null;//装载界面出单的合作伙伴的代理信息容器
				int errorCount = 0;
				//查询IN条件拼接的字符串
				String inSubDBTemConcatStr="";
				String channoCodeStr="";
				String inChannelDBTemConcatStr="";
				//提高性能算法从DB检查次数
				int totalRowCounts = sheet.getLastRowNum()+1;
				int checkFromDBCount=0;
				//每300条从数据库中查询是否满足条件
				if(totalRowCounts/300<0){
					checkFromDBCount=1;
				}else if(totalRowCounts/300>0){
					checkFromDBCount = totalRowCounts/300;
				}
				//声明个装载检查标识的容器
				List<Integer> checkDBCountLs = new  ArrayList<Integer>(checkFromDBCount);
				for(int i=1;i<=checkFromDBCount;i++){
					checkDBCountLs.add(Integer.valueOf(i*300));
				}
				//2.检查满足业务规范的数据进一步DB检查
				//2.1检查该用户下的所有的channelInfo是否满足权限并存在 且区分合作伙伴交易合作类型
				allChannelInfo = agentInfoMtDao.searchExistChannelInfoFromDB(user.getDepartmentStr());
				if(null!=allChannelInfo && allChannelInfo.size()>0){
					isFacadeChannelInfoLs = new ArrayList<String>(5);
					isFacadeAgentList = new ArrayList<TradAgentInfo>();
					for(TradAgentInfo tem1 :allChannelInfo){
						if("1".equals(tem1.getTransType())){//界面出单
							isFacadeChannelInfoLs.add(tem1.getChannelCode());
						}
					}
				}else{
					throw new AppException("上传失败:<br>当前登陆用户权限下不存在任何合作伙伴信息，请先申请权限后后导入<br>");
				}
				Map<String, String> map=new HashMap<String, String>();
				//2.2检查 subCode和用户代码 和 用户姓名是否为空
				Map<String, TradAgentInfo> channelMap=new HashMap<String, TradAgentInfo>();
				List<TradAgentInfo> infoList=new ArrayList<TradAgentInfo>();
				if(null!=list && list.size()>0){
					errorUserMsg=new ArrayList<TradAgentInfo>();
					infoList.addAll(list);
					for(int i=0;i<list.size();i++){
						channelMap.put(list.get(i).getChannelCode()+list.get(i).getSubChannelCode(), list.get(i));
						if(errorCount>9){
							excelIndexSubChannelInfo.clear();
							throw new AppException("上传失败:<br>"+errorBuf.toString());
						}
						if(checkDBCountLs.contains(i)){
							//DB检查数据库
							errorUserMsg = agentInfoMtDao.searchExistSubBranchCodeInfoFromDB(map);
							inSubDBTemConcatStr="";//清空
							channoCodeStr="";
							map=new HashMap<String, String>();
						}
						inSubDBTemConcatStr += "'"+list.get(i).getChannelCode()+list.get(i).getSubChannelCode()+"',";
					/*	channoCodeStr+="'"+list.get(i).getChannelCode()+"',";*/
						map.put("flag", inSubDBTemConcatStr.substring(0, inSubDBTemConcatStr.length()-1));
					/*	map.put("channoCode", channoCodeStr.substring(0, channoCodeStr.length()-1));*/
						//拼接channelCode
						if(!(inChannelDBTemConcatStr.contains(list.get(i).getChannelCode()))){
							inChannelDBTemConcatStr+= list.get(i).getChannelCode()+",";
						}
						excelIndexSubChannelInfo.put(list.get(i).getSubChannelCode(),list.get(i).getExcelRowIndex());//记录重复的userCode
						excelIndexChannelInfo.put(list.get(i).getChannelCode(),list.get(i).getExcelRowIndex());
					}
				}
				//最后一次检查DB
				if(StrUtil.isNotEmpty(inSubDBTemConcatStr)){
					//最后一次DB检查数据库
					List<TradAgentInfo> errorUserFinalMsg = agentInfoMtDao.searchExistSubBranchCodeInfoFromDB(map);
					errorUserMsg.addAll(errorUserFinalMsg);
				}
				/**取出所有已存在的用户*/
				List<TradAgentInfo>  agents=agentMap.get("update");
				for (TradAgentInfo info : errorUserMsg) {
					if(channelMap.get(info.getChannelCode()+info.getSubChannelCode())!=null){
						if(agents==null){
							agents=new ArrayList<TradAgentInfo>();
						}
						infoList.remove(channelMap.get(info.getChannelCode()+info.getSubChannelCode()));
						/**设置id*/
						TradAgentInfo upinfo=channelMap.get(info.getChannelCode()+info.getSubChannelCode());
						upinfo.setId(info.getId());
						agents.add(upinfo);
					}
				}
				agentMap.put("update", agents);
				/**取出所有需要保存的代理信息**/
				List<TradAgentInfo> adds=agentMap.get("add");
				if(adds==null){
					adds=infoList;
				}else{
					adds.addAll(infoList);
				}
				agentMap.put("add", adds);
				inSubDBTemConcatStr="";//清空
				//若有错误提示信息，则提示
				if(StrUtil.isNotEmpty(errorBuf.toString())){
					throw new AppException("上传失败:<br>"+errorBuf.toString());
				}
				excelIndexSubChannelInfo.clear();//清理掉map
				//2.3检查出单用户中的userCode是否有重复；
				if(null!=isFacadeAgentList && isFacadeAgentList.size()>0){
					for(int i = 0; i < isFacadeAgentList.size() - 1; i++){
						String userCode = isFacadeAgentList.get(i).getUserCode();
						if(errorCount>9){
							throw new AppException("上传失败:<br>"+errorBuf.toString());
						}
						for(int j = i + 1; j < isFacadeAgentList.size(); j++){
							if(userCode.equals(isFacadeAgentList.get(j).getUserCode())){
								errorBuf.append(" 第  "+isFacadeAgentList.get(i).getExcelRowIndex()+" 行与第 "+isFacadeAgentList.get(j).getExcelRowIndex()+" 行用户代码重复，请修改 <br>");
								errorCount++;
								continue;
							}
						}
					}
				}
				//若有错误提示信息，则提示
				if(StrUtil.isNotEmpty(errorBuf.toString())){
					throw new AppException("上传失败:<br>"+errorBuf.toString());
				}
				//2.4检查权限合作伙伴权限是否满足
				List<String> temChannelLs = new ArrayList<String>();
				for(TradAgentInfo tem :allChannelInfo){
					temChannelLs.add(tem.getChannelCode());
				}
				String[] StrArray = inChannelDBTemConcatStr.substring(0,inChannelDBTemConcatStr.length()-1).split(",");
				for(String tem :StrArray){
					if(errorCount>9){
						excelIndexChannelInfo.clear();
						throw new AppException("上传失败:<br>"+errorBuf.toString());
					}
					if(!temChannelLs.contains(tem)){
						errorBuf.append("第 "+excelIndexChannelInfo.get(tem)+"行的合作伙伴代码 "+tem+" 不存在或没有相关权限，请全列检查修改<br>");
						errorCount++;
					}
				}
				inChannelDBTemConcatStr ="";//清空
				//若有错误提示信息，则提示
				if(StrUtil.isNotEmpty(errorBuf.toString())){
					throw new AppException("上传失败:<br>"+errorBuf.toString());
				}
				excelIndexChannelInfo.clear();//清理掉map
				//2.5若存在总对总界面出单类型，则检查 userCode 是否在 t_facade_user表存在
				List<FacadeUser> errorExistUsers = new ArrayList<FacadeUser>();
				if(null!=isFacadeAgentList && isFacadeAgentList.size()>0){
					Map<String,Integer> userIndexMap = new HashMap<String, Integer>();
					String facadeUserCodeStr = "";
					for(int i= 0 ;i<isFacadeAgentList.size();i++){
						if(checkDBCountLs.contains(i)){
							try {
								errorExistUsers.addAll(userdao.queryUsersByUserCodeStr(facadeUserCodeStr.substring(0, facadeUserCodeStr.length()-1)));
							} catch (Exception e) {
								logger.error(e);
								throw new AppException("上传失败:查询用户名错误，请稍后重试！<br>");
							}
							facadeUserCodeStr="";//清空
						facadeUserCodeStr += "'"+list.get(i).getUserCode()+"',";
						userIndexMap.put(list.get(i).getUserCode(), list.get(i).getExcelRowIndex());
					}
					//追后一次检查DB
					if(StrUtil.isNotEmpty(facadeUserCodeStr)){
						//最后一次DB检查数据库
						try {
							errorExistUsers.addAll(userdao.queryUsersByUserCodeStr(facadeUserCodeStr.substring(0, facadeUserCodeStr.length()-1))) ;
						} catch (Exception e) {
							logger.error(e);
							throw new AppException("上传失败:查询用户名错误，请稍后重试！<br>");
						}
						facadeUserCodeStr="";//清空
					}
				  }
				}
				/**将所有已存在的usercode存入map**/
				Map<String, FacadeUser> userMap1=new HashMap<String, FacadeUser>();
				for (FacadeUser facadeUser : errorExistUsers) {
					userMap1.put(facadeUser.getUserCode(), facadeUser);
				}
				//若有错误提示信息，则提示
				if(StrUtil.isNotEmpty(errorBuf.toString())){
					throw new AppException("上传失败:<br>"+errorBuf.toString());
				}
				List<TradAgentInfo> subChannelList=agentMap.get("add");
				//3.都满足条件后，进行批量插入;
				List<GatewaySubChannel> userList = new ArrayList<GatewaySubChannel>();
				if(null!=list && list.size()>0){
					for(TradAgentInfo temAgent:subChannelList){
						//首先先检查否存在该子机构的信息
						GatewaySubChannel subChannelInfo = new GatewaySubChannel();
						subChannelInfo.setSubChannelCode(temAgent.getSubChannelCode());
						subChannelInfo.setSubChannelName(temAgent.getBranchName());
						subChannelInfo.setParentChannelCode(temAgent.getChannelCode());
						subChannelInfo.setZone(temAgent.getZone());
						subChannelInfo.setBranch(temAgent.getBranch());
						subChannelInfo.setBranchName(temAgent.getBranchName());
						subChannelInfo.setFkChannelCode(temAgent.getChannelCode());
						subChannelInfo.setOperUser(user.getUserid());
						//添加到facadeUser
						userList.add(subChannelInfo);
					}
				}
				if(null!=userList && userList.size()>0){
					subChannelDao.addBatchMtSubBranchInfo(userList);
				}
				if(null!=isFacadeAgentList && isFacadeAgentList.size()>0){
					List<FacadeUser> usersLs = new ArrayList<FacadeUser>();
					for(TradAgentInfo temUserInfo:isFacadeAgentList){
						/**已存在的usercode不保存*/
						if(userMap1.get(temUserInfo.getUserCode())!=null){
							continue;
						}
						FacadeUser facadeUser = new FacadeUser();
						facadeUser.setUserCode(temUserInfo.getUserCode());
						facadeUser.setUserName(temUserInfo.getUserName());
						facadeUser.setUserTypeCode("4");
						facadeUser.setfKSubChannelCode(temUserInfo.getSubChannelCode());
						facadeUser.setStatus(1);
						facadeUser.setFkChannelCode(temUserInfo.getChannelCode());
						facadeUser.setUserPwd(MD5Util.md5(temUserInfo.getUserCode()));
						//facadeUser.setOperTime(new Date());
						facadeUser.setOperUser(user.getUserid());
						//添加到facadeUser
						usersLs.add(facadeUser);
					}
					if(null!=usersLs && usersLs.size()>0){
						batchMtFacadeUserDao.addBatchMtFacadeUserInfo(usersLs);
					}
				}
			}
			/**需要更新的代理信息*/
			List<TradAgentInfo> updateInfo=agentMap.get("update");
			/**需要添加的代理信息*/
			List<TradAgentInfo> addInfo=agentMap.get("add");
			/**需要更新的代理信息**/
			Integer update=0;
			/**添加更新代理信息**/
			Integer add=0;
			if(null!=updateInfo&&updateInfo.size()>0){
				agentInfoMtDao.updateBachAgentInfo(updateInfo);
				update=updateInfo.size();
			}
			if(null!=addInfo && addInfo.size()>0){
				agentInfoMtDao.addBatchAgentInfo(addInfo);
				add=addInfo.size();
			}
			logger.info("插入信息代理信息: 添加 "+add+"更新"+update);
			session.setAttribute("result", "销售信息导入成功: 添加 "+add+"条  更新"+update+"条");
		}
		/*
		 * 检查sheet 是否满足业务规则校验,检查总对总代理类型
		 * 由于江苏邮政需求支持总对总界面出单改造
		 */
		private List<TradAgentInfo> importPreCheckSubBranchAgentTypeIsPassBusinessRule(HSSFSheet sheet,GatewayUser user) throws AppException {
	 		StringBuffer errorMsg = new StringBuffer();
			int errorCount = 0;
 			List<TradAgentInfo> temLs = new ArrayList<TradAgentInfo>();
			//当前登陆用户所属分公司两位机构代码
	 		String departmentStr = user.getDepartmentStr().substring(1, 3);
			for (int rowNum = 2; rowNum <= sheet.getLastRowNum(); rowNum++) {
				HSSFRow hssfRow = sheet.getRow(rowNum);
				//为了弹出界面简洁，限制输出10个错误；
				if(errorCount>10){
					throw new AppException("上传失败:<br>"+errorMsg.toString());
				}
				// 1、首先筛选排除空白行或者不满足录入列条件的行数据
				if (hssfRow == null) {
					continue;
				}else if(16>hssfRow.getLastCellNum()){
					errorMsg.append("总对总销售渠道信息第 "+(rowNum+1)+" 行数据未导入，原因：列长度不满足业务需求规则，请检查数据或模板有更新请重新下载模板 <br>");
					errorCount++;
					continue;
				}
				boolean flag = false; //是否为代理
				//空格检查
				if(StrUtil.isEmpty(ExcelUtil.getCellText(hssfRow.getCell(6)).trim())){
					errorMsg.append("总对总销售渠道信息第 "+(rowNum+1)+" 行，第 "+(7)+" 列数据为必录项不允许为空，请检查 <br>");
					errorCount++;
					continue;
				}
				String newBsnsType = ExcelUtil.getCellText(hssfRow.getCell(6)).trim();
				//新业务来源
				List<DictDto> newBSList = DictCache.getDict(Constants.DICT_NEW_BUSINESS_SOURCE);
				for (DictDto dictDto : newBSList) {
					if(dictDto.getCode().equals(newBsnsType)){
						if(dictDto.getCode2Name().contains("代理")){
							flag = true;
							break;
						}
					}
				}
				for (int colNum = 0; colNum < hssfRow.getLastCellNum(); colNum++) {
					//空格检查
					if(flag){
						if((StrUtil.isEmpty(ExcelUtil.getCellText(hssfRow.getCell(colNum)).trim()))){
							errorMsg.append("总对总销售渠道信息第 "+(rowNum+1)+" 行，第 "+(colNum+1)+" 列数据为必录项不允许为空，请检查 <br>");
							errorCount++;
							continue;
						}
					}else{
						if(7!=colNum && 8!=colNum && 9!=colNum && (StrUtil.isEmpty(ExcelUtil.getCellText(hssfRow.getCell(colNum)).trim()))){
							errorMsg.append("总对总销售渠道信息第 "+(rowNum+1)+" 行，第 "+(colNum+1)+" 列数据为必录项不允许为空，请检查 <br>");
							errorCount++;
							continue;
						}
					}
				}
				//校验导入出单机构代码：是否为登陆用户所属分公司下渠道信息
				if(!"00".equals(departmentStr) && !departmentStr.equals(ExcelUtil.getCellText(hssfRow.getCell(6)).trim().substring(0,2))){
					errorMsg.append("总对总销售渠道信息第 "+(rowNum+1)+" 行，出单机构代码"+ExcelUtil.getCellText(hssfRow.getCell(6)).trim()+"不存在或没有相关权限，请检查修改<br>");
					errorCount++;
					continue;
				}
				//为了弹出界面简洁，限制输出10个错误；
				if(errorCount>10){
					throw new AppException("上传失败:<br>"+errorMsg.toString());
				}
				//取单元格值
				String channelCode = ExcelUtil.getCellText(hssfRow.getCell(0)).trim();
				String branch = ExcelUtil.getCellText(hssfRow.getCell(1)).trim();
				String branchName = ExcelUtil.getCellText(hssfRow.getCell(2)).trim();
				String dptCde = ExcelUtil.getCellText(hssfRow.getCell(3)).trim();
				String channleCode = ExcelUtil.getCellText(hssfRow.getCell(4)).trim();
				String channleType = ExcelUtil.getCellText(hssfRow.getCell(5)).trim();
				String agentNo = ExcelUtil.getCellText(hssfRow.getCell(7)).trim();
				String cbrkrname = ExcelUtil.getCellText(hssfRow.getCell(8)).trim();
				String protocolNo = ExcelUtil.getCellText(hssfRow.getCell(9)).trim();
				String serviceCode = ExcelUtil.getCellText(hssfRow.getCell(10)).trim();
				String empName = ExcelUtil.getCellText(hssfRow.getCell(11)).trim();
				String empNo = "0";
				String managCode = ExcelUtil.getCellText(hssfRow.getCell(12)).trim();
				String manag = ExcelUtil.getCellText(hssfRow.getCell(13)).trim();
				String teamCode = ExcelUtil.getCellText(hssfRow.getCell(14)).trim();
				String teamName = ExcelUtil.getCellText(hssfRow.getCell(15)).trim();
				TradAgentInfo temObj = new TradAgentInfo();
				temObj.setAgentType("4");//由于之前已经校验，可以set 固定值；
				temObj.setExcelRowIndex(rowNum+1);
				temObj.setSubChannelCode(branch);
				temObj.setBranch(branch);
				temObj.setBranchName(branchName);
				temObj.setChannelCode(channelCode);
				temObj.setDptCde(dptCde);
				temObj.setChannleCode(channleCode);
				temObj.setChannleType(channleType);
				temObj.setNewBsnsType(newBsnsType);
				if(StrUtil.isNotEmpty(agentNo)){
					agentNo = "";
				}
				temObj.setAgentNo(agentNo);
				if(StrUtil.isNotEmpty(protocolNo)){
					protocolNo = "";
				}
				temObj.setProtocolNo(protocolNo);
				if(StrUtil.isNotEmpty(cbrkrname)){
					cbrkrname = "";
				}
				temObj.setCbrkrname(cbrkrname);
				temObj.setServiceCode(serviceCode);
				temObj.setEmpName(empName);
				temObj.setEmpNo(empNo);
				temObj.setTeamCode(teamCode);
				temObj.setTeamName(teamName);
				temObj.setManag(manag);
				temObj.setManag_code(managCode);
				temObj.setOperUser(user.getUserid());
				temLs.add(temObj);
			}
		/*	//3、校验excel中的子机构代码不能重复
			int checkUserCodeErrorCount=0;
			for(int i = 0; i < temLs.size() - 1; i++){
				String checkSubChannelCode = temLs.get(i).getSubChannelCode();
				if(checkUserCodeErrorCount>10){
					throw new AppException("上传失败:<br>"+errorMsg.toString());
				}
				for(int j = i + 1; j < temLs.size(); j++){
					if(checkSubChannelCode.equals(temLs.get(j).getSubChannelCode())){
						errorMsg.append("总对总销售渠道信息 第  "+(i+3)+" 行与第 "+(j+3)+" 行合作伙伴、区域代码、网点代码列组成的唯一标识重复，请修改 <br>");
						checkUserCodeErrorCount++;
						continue;
					}
				}
			}*/
			if(StrUtil.isNotEmpty(errorMsg.toString())){
				throw new AppException("上传失败:<br>"+errorMsg.toString());
			}
			return temLs;
		}
}
